package study.wechat.applet.auth;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import study.eggs.utils.WebUtils;
import study.wechat.applet.support.session.UserInfo;
import study.wechat.applet.support.session.UserInfoContext;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
@Order(1)
public class AuthFilter extends OncePerRequestFilter {

    private static final String X_TOKEN = "x-token";

    @Value("#{'${auth.ignore-list}'.split(',')}")
    public List<String> authcWhiteLt;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        try {
            //Step-1: ignore auth
            if (authcWhiteLt.contains(uri)) {
                doFilter(request, response, chain);
                return;
            }
            //Step-2: check token
            String token = WebUtils.getHeader(request, X_TOKEN);
            if (StrUtil.isEmpty(token)) {
                log.warn("Token Empty! [{}]", StrUtil.trimToEmpty(token));
                return;
            }
            //Step-3: acquire UserInfo
            UserInfo userInfo = null;
            //Step-4: hold UserInfo
            UserInfoContext.set(userInfo);

            //next filter
            doFilter(request, response, chain);
        } catch (Exception ex) {
            throw ex;
        } finally {
            UserInfoContext.remove();
        }
    }
}
